<?php
namespace app\admin\controller;
use app\admin\logic\LoginLogic;
use think\Controller;

/**
 * 登录api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/16
 * Time: 16:10
 */
class Login extends Base {

    public function __construct(){
        // parent::__construct();
        $this->l_logic = new LoginLogic();
    }

    /**
     * 超级管理员登录
     * @return \think\response\Json
     */
    public function ajax_admin_login(){
        $params = input();

        //检查登录规则
        $r = $this->l_logic->check_admin_login_rule($params);
        if(!$r['code']){
            return json($r);
        }
        $detail = $r['data']['detail'];

        session('admin_openid',$detail['openid']);
        $token = session_id();

        $data['token'] = $token;
        return json($this->l_logic->get_response(1,'登录成功',$data));
    }

    /**
     * 修改密码
     * @return \think\response\Json
     */
    public function ajax_save_password(){
        $params = input();

        $admin_openid = session('admin_openid');

        //检查更新密码规则
        $r = $this->l_logic->check_save_password_rule($admin_openid,$params);
        if(!$r['code']){
            return json($r);
        }
        $detail = $r['data']['detail'];

        $sure_password = md5(trim($params['sure_password']));

        $maps = [];
        $maps[] = ['id','=',$detail['id']];

        $u_data['password'] = $sure_password;
        $r = model('user')->force()->save($u_data,$maps);
        if($r !== false){
            return json($this->l_logic->get_response(1,'修改成功'));
        }
        return json($this->l_logic->get_response(0,'修改失败'));
    }

    /**
     * 获取二维码code
     * @return \think\response\Json
     */
    public function ajax_get_qrcode_code(){
        //删除之前的code
        $before_time = date('Y-m-d H:i:s',strtotime('-1 day'));
        $maps = [];
        $maps[] = ['openid','=',''];
        $maps[] = ['c_time','<',$before_time];
        $r = model('admin_login_code')->where($maps)->delete();

        $code = get_rand_str(32);
        $alc_data['code'] = $code;
        $alc_data['l_time'] = '0000-00-00 00:00:00';
        $r = model('admin_login_code')->insert($alc_data);
        if($r){
            $data['code'] = $code;
            return json($this->l_logic->get_response(1,'OK',$data));
        }
        return json($this->l_logic->get_response(0,'获取失败'));
    }

    /**
     * 二维码登录
     * @return \think\response\Json
     */
    public function ajax_qrcode_login(){
        $params = input();

        //检查二维码登录规则
        $r = $this->l_logic->check_qrcode_login_rule($params);
        if($r['code'] != 1){
            return json($r);
        }
        $u_detail = $r['data']['u_detail'];

        session('admin_openid',$u_detail['openid']);
        $token = session_id();

        $data['token'] = $token;
        return json($this->l_logic->get_response(1,'登录成功',$data));
    }
}